package com.shipwe.loans.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import com.shipwe.loans.R
import com.shipwe.loans.base.app.ShipweStackManager
import com.shipwe.loans.databinding.ActivityLoginBinding
import com.shipwe.loans.pro.ShipweActivity
import com.shipwe.loans.ui.presenter.UserLoginPresenter
import com.shipwe.loans.ui.view.IUserLoginView
import com.shipwe.loans.utils.event.AppEventPointType
import com.shipwe.loans.utils.helper.CustomConfigsHelper
import com.shipwe.loans.utils.shared.ShipweSharedHelper
import com.shipwe.loans.utils.shared.ShipweSharedKey
import org.json.JSONObject

/**
 * Shipwe
 * @Author wwdeng
 * @CreateTime: 2024/11/11 16:48
 * @Annotation：登录
 */
class ActivityLogin: ShipweActivity(),IUserLoginView {
    lateinit var binding: ActivityLoginBinding
    private var presenter: UserLoginPresenter? = null

    override fun getShipweRootView(): View? {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initShipweView() {
        rootViewBinding.rootLayout.setBackgroundResource(R.drawable.page_login_bg)
        setShipweTitleBarVisibility(View.VISIBLE)
        setShipweBackBtnVisibility(View.GONE)
        setShipweRightBtnRes(R.drawable.customer_black)
        setShipweTextTitle("")
        //关闭所有页面
        ShipweStackManager.finishAllActivity(ActivityLogin::class.java)
        checkLoginBtnState()
    }

    override fun initShipweListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog("Login Page")
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_CUSTOMER,"Login Page")
        }

        binding.userLoginMobile.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {
                }
                else -> {
                    appEventPointRequestAction(AppEventPointType.FORM.SHIPWE_FORM_LOGIN_MOBILE, getUserLoginMobile())
                }
            }
        }
        //电话号码入框监听
        binding.userLoginMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkLoginBtnState()
            }
        })
        binding.userLoginMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.userLoginMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.userLoginCheckBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOGIN_PRIVACY_AGREE)
                }
                false -> {
                    appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //登录
        binding.userLoginButton.setOnClickListener {
            appEventPointRequestAction(AppEventPointType.CLICK.SHIPWE_CLICK_LOGIN_NEXT)
            onHideSoftInput(binding.userLoginMobile)
            presenter?.requestUserLoginAction()
        }

        //隐私协议
        binding.userLoginPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.privacy_policy_title)
            val linkUrl = CustomConfigsHelper.getShipwePrivacyPolicyLink()
            ActivityWebView.start(this,showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initShipweData() {
        presenter = UserLoginPresenter(this)
        binding.userLoginZoneCode.text = "+${ShipweSharedHelper.getShipweSharedString(ShipweSharedKey.SHIPWE_TIMEZONE_CODE)}"

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.privacy_policy_title))
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#343434")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.userLoginPrivacyPolicy.text = spString
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        binding.userLoginMobileError.visibility = View.GONE
        binding.userLoginMobileViewGroup.setBackgroundResource(R.drawable.circle_white)
        binding.userLoginZoneCode.setTextColor(Color.parseColor("#FF2C2C2C"))
        binding.userLoginLine.setBackgroundColor(Color.parseColor("#FFBEBFC2"))
        binding.userLoginMobile.setTextColor(Color.parseColor("#FF2C2C2C"))
        if (binding.userLoginCheckBox.isChecked && getUserLoginMobile().isNotEmpty()) {
            binding.userLoginButton.isEnabled = true
        } else {
            binding.userLoginButton.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    override fun getUserLoginMobile(): String {
        return binding.userLoginMobile.text.toString().trim()
    }

    override fun showUserLoginFailure(data: JSONObject) {
        binding.userLoginMobileViewGroup.setBackgroundResource(R.drawable.circle_frame_ffff4d3e)
        binding.userLoginZoneCode.setTextColor(Color.parseColor("#FFFF4D3E"))
        binding.userLoginLine.setBackgroundColor(Color.parseColor("#FFFF4D3E"))
        binding.userLoginMobile.setTextColor(Color.parseColor("#FFFF4D3E"))
        binding.userLoginMobileError.visibility = View.VISIBLE
    }

    override fun showUserLoginMainPage() {
        onIntent(ActivityMain::class.java)
        finish()
    }

    override fun onStart() {
        super.onStart()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        appEventPointRequestAction(AppEventPointType.PAGE.SHIPWE_PAGE_LOGIN_END)
    }
}